﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace InfoPathHelpers.Cryptography
{
    public static class RSAHelper
    {
        public static RSACryptoServiceProvider GetRSACryptoProvider(string containerName)
        {
            return GetRSACryptoProvider(containerName, true);
        }

        public static RSACryptoServiceProvider GetRSACryptoProvider(string containerName, bool persist)
        {
            var ProviderParameters = new CspParameters()
            {
                KeyContainerName = containerName
            };

            return new RSACryptoServiceProvider(ProviderParameters) { PersistKeyInCsp = persist };
        }

        public static RSACryptoServiceProvider GetRSACryptoProvider(X509Certificate2 certificate, RSAKeyType keyType)
        {
            RSACryptoServiceProvider CryptoServiceProvider = null;
            switch(keyType)
            {
                case RSAKeyType.Private:
                    if (certificate.HasPrivateKey)
                    {
                        CryptoServiceProvider = (RSACryptoServiceProvider)certificate.PrivateKey;
                    }
                    else
                    {
                        throw new ArgumentException("The certificate does not have a private key", "keyType");
                    }
                    break;
                case RSAKeyType.Public:
                    CryptoServiceProvider = (RSACryptoServiceProvider)certificate.PublicKey.Key;
                    break;
            }
            
            return CryptoServiceProvider;
        }
    }

    public enum RSAKeyType
    {
        Public,
        Private
    }
}
